import React, { useState, useEffect } from 'react';
import { RoleEditor } from './components/ui/RoleEditor';
import Login from './components/Login';
import ConfirmModal from './components/ConfirmModal';
import MemoModal from './components/MemoModal';
import EditConfirmModal from './components/EditConfirmModal';

// 简单的Markdown解析函数
const parseMarkdown = (text: string) => {
  return text
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>') // **加粗**
    .replace(/\*(.*?)\*/g, '<em>$1</em>') // *斜体*
    .replace(/### (.*?)(?=\n|$)/g, '<h3 class="text-base font-bold mb-2 text-gray-800 mt-4">$1</h3>') // ### 标题
    .replace(/## (.*?)(?=\n|$)/g, '<h2 class="text-lg font-bold mb-3 text-gray-900 mt-4">$1</h2>') // ## 标题  
    .replace(/# (.*?)(?=\n|$)/g, '<h1 class="text-xl font-bold mb-4 text-gray-900 border-b pb-2 mt-4">$1</h1>') // # 标题
    .replace(/^- (.*?)(?=\n|$)/gm, '<li class="ml-4 list-disc">$1</li>') // - 列表项
    .replace(/^(\d+)\. (.*?)(?=\n|$)/gm, '<li class="ml-4 list-decimal">$1. $2</li>'); // 1. 数字列表
};

function App() {
  // 从localStorage恢复消息历史
  const loadMessagesFromStorage = () => {
    try {
      const saved = localStorage.getItem('mindmate_messages');
      if (saved) {
        const parsed = JSON.parse(saved);
        return parsed.map((msg: any) => ({
          ...msg,
          timestamp: new Date(msg.timestamp)
        }));
      }
    } catch (error) {
      console.warn('加载消息历史失败:', error);
    }
    
    // 默认欢迎消息
    return [
      {
        id: '1',
        role: 'assistant' as const,
        content: '您好！我是Emma，很高兴为您提供心理咨询服务。请随时告诉我您想要讨论的话题或遇到的困扰。',
        timestamp: new Date()
      }
    ];
  };

  // 从localStorage恢复当前角色
  const loadCurrentRoleFromStorage = () => {
    try {
      return localStorage.getItem('mindmate_current_role') || 'emma';
    } catch (error) {
      return 'emma';
    }
  };

  // 消息状态管理
  const [messages, setMessages] = useState<Array<{id: string, role: 'user' | 'assistant', content: string, timestamp: Date}>>(loadMessagesFromStorage);
  const [inputValue, setInputValue] = useState('');
  const [currentRole, setCurrentRole] = useState(loadCurrentRoleFromStorage);
  const [isLoading, setIsLoading] = useState(false);

  // 备忘录状态管理
  const [currentMemo, setCurrentMemo] = useState('');
  const [memoCreatedAt, setMemoCreatedAt] = useState('');
  const [isMemoDialogOpen, setIsMemoDialogOpen] = useState(false);
  const [isEditingMemo, setIsEditingMemo] = useState(false);
  const [tempMemo, setTempMemo] = useState('');
  
  // 对话轮次提醒
  const [conversationTurns, setConversationTurns] = useState(0);
  const [showTurnWarning, setShowTurnWarning] = useState(false);

  // 模型状态管理
  const [availableModels, setAvailableModels] = useState<Array<any>>([]);
  const [currentModel, setCurrentModel] = useState('doubao-seed-1-6-250615');
  const [isModelSelectorOpen, setIsModelSelectorOpen] = useState(false);
  
  // 用户认证状态
  const [currentUser, setCurrentUser] = useState<any>(null);
  const [showLoginDialog, setShowLoginDialog] = useState(false);
  const [isCheckingAuth, setIsCheckingAuth] = useState(true);
  const [isRoleSelectorOpen, setIsRoleSelectorOpen] = useState(false);
  const [isLoadingModels, setIsLoadingModels] = useState(false);

  // 角色配置
  const roleConfigs = [
    {
      id: 'emma',
      name: 'Emma',
      title: '心理咨询师',
      icon: '👩‍⚕️',
      description: '温暖专业的心理咨询师，具有丰富的临床经验和深厚的同理心',
      features: ['情感支持', '压力管理', '人际关系', '心理疏导'],
      color: 'purple',
      systemPrompt: '你是Emma，一位温暖专业的心理咨询师，具有丰富的临床经验和深厚的同理心。你善于倾听、理解，并能给出专业而贴心的心理建议。请用温和、支持性的语调与用户交流，帮助他们解决情感和心理问题。'
    },
    {
      id: 'sophie',
      name: 'Sophie', 
      title: '学术助手',
      icon: '👩‍🎓',
      description: '严谨的学术研究助手，提供专业的学术指导和研究支持',
      features: ['学术研究', '知识问答', '文献分析', '论文指导'],
      color: 'indigo',
      systemPrompt: '你是Sophie，一位严谨的学术研究助手。你擅长提供专业的学术指导、研究支持、文献分析和论文指导。请用专业、准确、逻辑清晰的方式回答问题，注重事实依据和学术规范。'
    },
    {
      id: 'mike',
      name: 'Mike',
      title: '面试教练', 
      icon: '👨‍💼',
      description: '经验丰富的面试教练，帮助您在求职中脱颖而出',
      features: ['面试技巧', '职业规划', '简历优化', '模拟面试'],
      color: 'emerald',
      systemPrompt: '你是Mike，一位经验丰富的面试教练和职业规划专家。你专注于帮助求职者提升面试技巧、优化简历、规划职业发展。请用专业、鼓励且实用的语调提供建议，帮助用户在求职中脱颖而出。'
    }
  ];

  // 对话增强状态管理
  const [messageActions, setMessageActions] = useState<{[key: string]: boolean}>({});
  const [isThinking, setIsThinking] = useState(false);
  const [thinkingRole, setThinkingRole] = useState('');
  const [regeneratingMessageId, setRegeneratingMessageId] = useState<string | null>(null);

  // 会话管理状态
  const [sessions, setSessions] = useState<Array<any>>([]);
  const [currentSessionId, setCurrentSessionId] = useState<string | null>(null);
  const [isSessionListOpen, setIsSessionListOpen] = useState(true);
  const [sessionSearchQuery, setSessionSearchQuery] = useState('');
  const [sessionFilter, setSessionFilter] = useState(''); // '', 'favorite', 'archived'
  const [isLoadingSessions, setIsLoadingSessions] = useState(false);
  const [sessionPage, setSessionPage] = useState(1);
  const [sessionPagination, setSessionPagination] = useState({ total: 0, totalPages: 0 });

  // 确认删除弹窗状态
  const [confirmModal, setConfirmModal] = useState<{
    isOpen: boolean;
    title: string;
    message: string;
    onConfirm: () => void;
    sessionTitle?: string;
  }>({
    isOpen: false,
    title: '',
    message: '',
    onConfirm: () => {},
  });

  // 备忘录Modal状态
  const [memoModal, setMemoModal] = useState<{
    isOpen: boolean;
    sessionId: string;
    sessionTitle: string;
  }>({
    isOpen: false,
    sessionId: '',
    sessionTitle: '',
  });

  // 搜索功能状态
  const [isSearchEnabled, setIsSearchEnabled] = useState(true);

  // 消息编辑状态
  const [editingMessageId, setEditingMessageId] = useState<string | null>(null);
  const [editingContent, setEditingContent] = useState("");
  const [showEditConfirm, setShowEditConfirm] = useState(false);
  const [editPreview, setEditPreview] = useState<{
    deleteCount: number;
    previewMessages: Array<{role: string; content: string}>;
    hasMore: boolean;
    memoImpact: 'none' | 'will_regenerate' | 'will_clear';
    currentMemoExists: boolean;
  } | null>(null);
  const [memoOutdated, setMemoOutdated] = useState(false);

  // 自定义角色状态
  const [customRoles, setCustomRoles] = useState<Array<any>>([]);
  const [isRoleEditorOpen, setIsRoleEditorOpen] = useState(false);
  const [editingRole, setEditingRole] = useState<any>(null);
  const [isLoadingRoles, setIsLoadingRoles] = useState(false);
  
  // 角色切换确认对话框状态
  const [isRoleSwitchModalOpen, setIsRoleSwitchModalOpen] = useState(false);
  const [pendingRoleId, setPendingRoleId] = useState<string | null>(null);

  // 保存消息到localStorage
  const saveMessagesToStorage = (newMessages: Array<{id: string, role: 'user' | 'assistant', content: string, timestamp: Date}>) => {
    try {
      localStorage.setItem('mindmate_messages', JSON.stringify(newMessages));
    } catch (error) {
      console.warn('保存消息历史失败:', error);
    }
  };

  // 保存当前角色到localStorage
  const saveCurrentRoleToStorage = (role: string) => {
    try {
      localStorage.setItem('mindmate_current_role', role);
    } catch (error) {
      console.warn('保存角色设置失败:', error);
    }
  };

  // 监听messages变化，自动保存
  React.useEffect(() => {
    saveMessagesToStorage(messages);
  }, [messages]);

  // 监听currentRole变化，自动保存
  React.useEffect(() => {
    saveCurrentRoleToStorage(currentRole);
  }, [currentRole]);

  // 加载可用模型列表
  const loadAvailableModels = async () => {
    try {
      setIsLoadingModels(true);
      console.log('开始加载模型列表...');
      const response = await fetch('/api/models');
      
      if (!response.ok) {
        throw new Error(`获取模型列表失败: ${response.status}`);
      }
      
      const data = await response.json();
      console.log('模型数据:', data);
      setAvailableModels(data.models || []);
      setCurrentModel(data.current || 'doubao-seed-1-6-250615');
      console.log('模型加载完成，模型数量:', (data.models || []).length);
      
    } catch (error) {
      console.error('加载模型列表失败:', error);
      // 设置默认模型以避免显示问题
      setAvailableModels([]);
    } finally {
      setIsLoadingModels(false);
    }
  };

  // 切换模型
  const switchModel = async (modelId: string) => {
    try {
      const response = await fetch('/api/models/switch', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ model_id: modelId })
      });
      
      const data = await response.json();
      
      if (data.success) {
        setCurrentModel(modelId);
        console.log(`切换到模型: ${modelId}`);
      } else {
        console.error('切换模型失败:', data.message);
      }
    } catch (error) {
      console.error('切换模型时出错:', error);
    }
  };

  // 会话管理函数
  const loadSessions = async () => {
    try {
      setIsLoadingSessions(true);
      const response = await fetch(`/api/sessions?query=${sessionSearchQuery}&page=${sessionPage}&pageSize=20&filter=${sessionFilter}`);
      const data = await response.json();
      
      if (sessionPage === 1) {
        setSessions(data.sessions || []);
      } else {
        setSessions(prev => [...prev, ...(data.sessions || [])]);
      }
      
      setSessionPagination({
        total: data.pagination?.total || 0,
        totalPages: data.pagination?.totalPages || 0
      });
    } catch (error) {
      console.error('加载会话列表失败:', error);
    } finally {
      setIsLoadingSessions(false);
    }
  };

  const createNewSession = async () => {
    try {
      const roleInfo = getCurrentRoleInfo();
      const response = await fetch('/api/sessions', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          title: `与${roleInfo.name}的对话`,
          roleId: currentRole,
          model: currentModel,
          searchEnabled: true
        })
      });
      const result = await response.json();
      
      if (result.success) {
        // 切换到新会话
        setCurrentSessionId(result.data.id);
        // 清空当前消息
        setMessages([]);
        // 重新加载会话列表
        setSessionPage(1);
        loadSessions();
      }
    } catch (error) {
      console.error('创建会话失败:', error);
    }
  };

  const switchToSession = async (sessionId: string) => {
    try {
      setCurrentSessionId(sessionId);
      
      // 获取会话详情和消息
      const response = await fetch(`/api/sessions/${sessionId}`);
      const result = await response.json();
      
      if (result.success) {
        const sessionData = result.data;
        
        // 更新会话相关状态
        setCurrentRole(sessionData.roleId || 'emma');
        // 保持用户当前选择的模型，不重置为会话模型
        
        // 加载搜索设置
        setIsSearchEnabled(sessionData.searchEnabled ?? true);
        
        // 加载会话消息
        const sessionMessages = sessionData.messages?.map((msg: any) => ({
          id: msg.id,
          role: msg.role,
          content: msg.content,
          timestamp: new Date(msg.timestamp)
        })) || [];
        
        setMessages(sessionMessages);
        
        // 加载备忘录
        await loadSessionMemo(sessionId);
        
        // 更新对话轮次统计
        updateConversationTurns(sessionMessages);
      }
    } catch (error) {
      console.error('切换会话失败:', error);
    }
  };

  const renameSession = async (sessionId: string, newTitle: string) => {
    try {
      const response = await fetch(`/api/sessions/${sessionId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ title: newTitle })
      });
      
      if (response.ok) {
        // 更新本地会话列表
        setSessions(prev => prev.map(s => 
          s.id === sessionId ? { ...s, title: newTitle } : s
        ));
      }
    } catch (error) {
      console.error('重命名会话失败:', error);
    }
  };

  const toggleSearchEnabled = async (enabled: boolean) => {
    if (!currentSessionId) return;
    
    try {
      const response = await fetch(`/api/sessions/${currentSessionId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ searchEnabled: enabled })
      });
      
      if (response.ok) {
        setIsSearchEnabled(enabled);
        // 更新本地会话列表
        setSessions(prev => prev.map(s => 
          s.id === currentSessionId ? { ...s, searchEnabled: enabled } : s
        ));
      }
    } catch (error) {
      console.error('更新搜索设置失败:', error);
    }
  };

  const toggleFavoriteSession = async (sessionId: string) => {
    try {
      const session = sessions.find(s => s.id === sessionId);
      if (!session) return;
      
      const response = await fetch(`/api/sessions/${sessionId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ isFavorite: !session.isFavorite })
      });
      
      if (response.ok) {
        setSessions(prev => prev.map(s => 
          s.id === sessionId ? { ...s, isFavorite: !s.isFavorite } : s
        ));
      }
    } catch (error) {
      console.error('切换收藏状态失败:', error);
    }
  };

  const deleteSession = async (sessionId: string) => {
    try {
      const response = await fetch(`/api/sessions/${sessionId}`, {
        method: 'DELETE'
      });
      
      if (response.ok) {
        // 如果删除的是当前会话，切换到第一个可用会话或创建新会话
        if (currentSessionId === sessionId) {
          const remainingSessions = sessions.filter(s => s.id !== sessionId && !s.isArchived);
          if (remainingSessions.length > 0) {
            switchToSession(remainingSessions[0].id);
          } else {
            createNewSession();
          }
        }
        
        // 重新加载会话列表
        setSessionPage(1);
        loadSessions();
      }
    } catch (error) {
      console.error('删除会话失败:', error);
    }
  };

  // 备忘录管理函数
  const loadSessionMemo = async (sessionId: string) => {
    try {
      const response = await fetch(`/api/sessions/${sessionId}/memo`);
      const data = await response.json();
      
      if (response.ok && data.success) {
        setCurrentMemo(data.data.memo || '');
        setMemoCreatedAt(data.data.memo_created_at || '');
      }
    } catch (error) {
      console.error('加载备忘录失败:', error);
    }
  };

  const updateSessionMemo = async (sessionId: string, memo: string) => {
    try {
      const response = await fetch(`/api/sessions/${sessionId}/memo`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ memo })
      });
      const data = await response.json();
      
      if (response.ok && data.success) {
        setCurrentMemo(memo);
        setMemoCreatedAt(data.data.memo_created_at);
        return true;
      }
      return false;
    } catch (error) {
      console.error('更新备忘录失败:', error);
      return false;
    }
  };

  const regenerateSessionMemo = async (sessionId: string) => {
    try {
      const response = await fetch(`/api/sessions/${sessionId}/memo/regenerate`, {
        method: 'POST'
      });
      const data = await response.json();
      
      if (response.ok && data.success) {
        setCurrentMemo(data.data.memo);
        setMemoCreatedAt(data.data.memo_created_at);
        return true;
      }
      return false;
    } catch (error) {
      console.error('重新生成备忘录失败:', error);
      return false;
    }
  };

  // 计算对话轮次并检查是否需要警告
  const updateConversationTurns = (messages: any[]) => {
    const turns = Math.floor(messages.length / 2);
    setConversationTurns(turns);
    
    // 当接近阈值时显示警告 (4轮以上显示警告)
    if (turns >= 4 && turns < 5) {
      setShowTurnWarning(true);
    } else if (turns >= 5) {
      // 超过阈值后不显示警告，因为已经生成备忘录了
      setShowTurnWarning(false);
    } else {
      setShowTurnWarning(false);
    }
  };

  // 自定义角色管理函数
  const loadCustomRoles = async () => {
    try {
      setIsLoadingRoles(true);
      const response = await fetch('/api/roles');
      const data = await response.json();
      
      if (response.ok) {
        setCustomRoles(data.custom || []);
      } else {
        console.error('加载自定义角色失败:', data.detail);
      }
    } catch (error) {
      console.error('加载自定义角色失败:', error);
    } finally {
      setIsLoadingRoles(false);
    }
  };

  const handleSaveRole = async (roleData: {name: string, input_spec: string, output_spec: string, custom_traits?: Array<{key: string, value: string}>}) => {
    try {
      let savedRole = null;
      
      if (editingRole) {
        // 编辑模式
        const response = await fetch(`/api/roles/${editingRole.id}`, {
          method: 'PATCH',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(roleData)
        });
        const data = await response.json();
        if (!response.ok) throw new Error(data.detail || '更新角色失败');
        savedRole = data.data;
      } else {
        // 创建模式
        const response = await fetch('/api/roles', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(roleData)
        });
        const data = await response.json();
        if (!response.ok) throw new Error(data.detail || '创建角色失败');
        savedRole = data.data;
      }

      // 重新加载角色列表
      await loadCustomRoles();
      
      // 关闭编辑器
      closeRoleEditor();
      
      // 如果是创建模式，可以选择切换到新角色
      if (!editingRole && savedRole) {
        const shouldSwitchToNewRole = confirm(`角色"${roleData.name}"创建成功！是否立即切换到此角色？`);
        if (shouldSwitchToNewRole) {
          await handleRoleChange(savedRole.id);
        }
      }
    } catch (error) {
      console.error('保存角色失败:', error);
      alert('保存角色失败：' + (error instanceof Error ? error.message : '未知错误'));
      throw error;
    }
  };

  const deleteCustomRole = async (roleId: string) => {
    try {
      const response = await fetch(`/api/roles/${roleId}`, {
        method: 'DELETE'
      });
      
      const data = await response.json();
      
      if (response.ok) {
        await loadCustomRoles();
        console.log('角色删除成功:', data.message);
        
        if (currentRole === roleId) {
          setCurrentRole('emma');
        }
      } else {
        throw new Error(data.detail || '删除角色失败');
      }
    } catch (error) {
      console.error('删除角色失败:', error);
      throw error;
    }
  };

  const openRoleEditor = (role: any = null) => {
    setEditingRole(role);
    setIsRoleEditorOpen(true);
  };

  const closeRoleEditor = () => {
    setEditingRole(null);
    setIsRoleEditorOpen(false);
  };

  // ========================= 消息编辑功能 =========================

  const startEditMessage = (message: any) => {
    if (message.role !== 'user') return;
    console.log('开始编辑消息:', { messageId: message.id, sessionId: currentSessionId, content: message.content });
    setEditingMessageId(message.id);
    setEditingContent(message.content);
  };

  const cancelEdit = () => {
    setEditingMessageId(null);
    setEditingContent("");
  };

  const handleEditKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleEditSubmit();
    } else if (e.key === 'Escape') {
      cancelEdit();
    }
  };

  const handleEditSubmit = async () => {
    console.log('提交编辑:', { editingMessageId, currentSessionId, editingContent });
    
    if (!editingMessageId) {
      console.error('没有要编辑的消息ID');
      return;
    }
    
    if (!currentSessionId) {
      alert('编辑功能需要在会话中使用，请先选择或创建一个会话');
      return;
    }
    
    // 获取原消息
    const originalMessage = messages.find(m => m.id === editingMessageId);
    console.log('找到原消息:', originalMessage);
    
    if (!originalMessage || editingContent.trim() === originalMessage.content.trim()) {
      console.log('消息未变更，取消编辑');
      cancelEdit();
      return;
    }
    
    // 获取编辑预览
    try {
      const response = await fetch(
        `/api/sessions/${currentSessionId}/messages/${editingMessageId}/edit-preview`
      );
      const data = await response.json();
      
      if (data.success) {
        setEditPreview({
          deleteCount: data.data.delete_count,
          previewMessages: data.data.preview_messages || [],
          hasMore: data.data.has_more || false,
          memoImpact: data.data.memo_impact || 'none',
          currentMemoExists: data.data.current_memo_exists || false
        });
        
        if (data.data.delete_count > 0) {
          setShowEditConfirm(true);
        } else {
          await submitEdit(true);
        }
      }
    } catch (error) {
      console.error('获取编辑预览失败:', error);
      alert('获取编辑预览失败，请重试');
    }
  };

  const submitEdit = async (autoRegenerateMemo: boolean = true) => {
    if (!editingMessageId) {
      console.error('没有要编辑的消息ID');
      return;
    }
    
    if (!currentSessionId) {
      alert('编辑功能需要在会话中使用，请先选择或创建一个会话');
      return;
    }
    
    try {
      const response = await fetch(
        `/api/sessions/${currentSessionId}/messages/${editingMessageId}`,
        {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ 
            content: editingContent.trim(),
            auto_regenerate: autoRegenerateMemo
          })
        }
      );
      
      const data = await response.json();
      
      if (data.success) {
        // 更新消息列表
        const updatedMessages = data.data.messages.map((msg: any) => ({
          ...msg,
          timestamp: new Date(msg.timestamp)
        }));
        setMessages(updatedMessages);
        
        // 处理备忘录状态
        if (data.data.memo_status === 'regenerated') {
          setCurrentMemo(data.data.current_memo || '');
          setMemoCreatedAt(new Date().toISOString());
          console.log('备忘录已自动更新');
        } else if (data.data.memo_status === 'need_clear' || data.data.memo_status === 'cleared') {
          setCurrentMemo('');
          setMemoCreatedAt('');
        } else if (data.data.memo_affected && !data.data.memo_regenerated) {
          // 备忘录可能过时但未自动更新
          setMemoOutdated(true);
        }
        
        // 清理状态
        cancelEdit();
        setShowEditConfirm(false);
        setEditPreview(null);
        
        // 显示成功提示
        console.log(data.message);
        
        // 如果最后一条是用户消息，自动触发AI回复
        const lastMessage = updatedMessages[updatedMessages.length - 1];
        if (lastMessage && lastMessage.role === 'user') {
          console.log('检测到用户消息，准备生成AI回复...');
          // 延迟一下让UI更新完成
          setTimeout(() => {
            generateAIResponseForEditedMessage(lastMessage.content);
          }, 100);
        }
      } else {
        alert(data.message || '编辑失败');
      }
    } catch (error) {
      console.error('编辑消息失败:', error);
      alert('编辑失败，请重试');
    }
  };

  // 为编辑后的消息生成AI回复
  const generateAIResponseForEditedMessage = async (userMessage: string) => {
    if (!currentSessionId) return;
    
    try {
      setIsLoading(true);
      
      // 构建消息上下文
      const roleInfo = getCurrentRoleInfo();
      const systemPrompt = roleInfo.systemPrompt || 
        `你是${roleInfo.name}，${roleInfo.description}。请用${roleInfo.title}的专业角度回答问题。`;
      
      const contextMessages = [
        { role: 'system', content: systemPrompt },
        ...messages.map(msg => ({
          role: msg.role,
          content: msg.content
        }))
      ];
      
      console.log('发送AI请求，消息上下文长度:', contextMessages.length);
      
      // 调用AI API
      const response = await fetch('/api/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ 
          messages: contextMessages,
          model: currentModel,
          searchEnabled: isSearchEnabled
        })
      });
      
      const data = await response.json();
      
      if (response.ok) {
        const aiContent = data.content;
        console.log('AI回复成功，长度:', aiContent.length);
        
        // 添加AI回复到UI
        const aiMessage = {
          id: (Date.now() + 1).toString(),
          role: 'assistant' as const,
          content: aiContent,
          timestamp: new Date()
        };
        
        setMessages(prev => [...prev, aiMessage]);
        
        // 添加AI回复到会话
        await fetch(`/api/sessions/${currentSessionId}/messages`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            role: 'assistant',
            content: aiContent
          })
        });
        
        console.log('AI回复已添加到会话');
      } else {
        console.error('AI回复失败:', data);
      }
    } catch (error) {
      console.error('生成AI回复时出错:', error);
    } finally {
      setIsLoading(false);
    }
  };

  // 备忘录过时提示组件
  const MemoOutdatedBanner = () => {
    if (!memoOutdated || !currentMemo) return null;
    
    return (
      <div className="fixed top-16 left-1/2 transform -translate-x-1/2 bg-amber-50 border border-amber-200 rounded-lg p-3 flex items-center gap-4 shadow-lg z-50 slide-down">
        <div className="flex items-center gap-2">
          <span className="text-lg">💡</span>
          <span className="text-amber-800 text-sm font-medium">对话摘要可能已过时</span>
        </div>
        <div className="flex gap-2">
          <button 
            className="px-3 py-1 bg-amber-500 text-white text-sm rounded hover:bg-amber-600 transition-colors"
            onClick={async () => {
              try {
                const response = await fetch(
                  `/api/sessions/${currentSessionId}/memo/regenerate`,
                  { method: 'POST' }
                );
                if (response.ok) {
                  const data = await response.json();
                  if (data.success) {
                    setCurrentMemo(data.data.memo);
                    setMemoCreatedAt(data.data.memo_created_at);
                    setMemoOutdated(false);
                  }
                }
              } catch (error) {
                console.error('更新摘要失败:', error);
              }
            }}
          >
            更新摘要
          </button>
          <button 
            className="px-3 py-1 bg-gray-100 text-gray-600 text-sm rounded hover:bg-gray-200 transition-colors"
            onClick={() => setMemoOutdated(false)}
          >
            知道了
          </button>
        </div>
      </div>
    );
  };

  // 获取角色信息（支持预设和自定义角色）
  const getRoleInfo = (roleId: string) => {
    // 先查找预设角色
    const presetRole = roleConfigs.find(r => r.id === roleId);
    if (presetRole) {
      return {
        ...presetRole,
        systemPrompt: presetRole.systemPrompt,
        isCustom: false
      };
    }
    
    // 查找自定义角色
    const customRole = customRoles.find(r => r.id === roleId);
    if (customRole) {
      return {
        id: customRole.id,
        name: customRole.name,
        title: customRole.title || customRole.name, // 使用专门的title字段，fallback到name
        icon: '🎭',
        color: 'emerald', // 自定义角色统一使用绿色主题
        description: `输入：${customRole.input_spec}`,
        features: customRole.custom_traits ? customRole.custom_traits.map(trait => `${trait.key}：${trait.value}`) : ['自定义规范'],
        systemPrompt: customRole.system_prompt_snapshot,
        isCustom: true
      };
    }
    
    // 默认返回第一个预设角色
    return {
      ...roleConfigs[0],
      systemPrompt: roleConfigs[0].systemPrompt,
      isCustom: false
    };
  };

  // 获取当前角色信息（支持预设和自定义角色）
  const getCurrentRoleInfo = () => {
    return getRoleInfo(currentRole);
  };
  
  // 处理登录成功
  const handleLoginSuccess = (user: any) => {
    setCurrentUser(user);
    setShowLoginDialog(false);
    // 重新加载会话列表
    loadSessions();
  };
  
  // 处理登出
  const handleLogout = () => {
    localStorage.removeItem('mindmate_token');
    localStorage.removeItem('mindmate_user');
    setCurrentUser(null);
    setSessions([]);
    setMessages([]);
    setCurrentSessionId(null);
  };

  // 组件初始化时加载模型列表、会话列表和自定义角色列表
  // 检查用户认证状态
  React.useEffect(() => {
    const checkAuth = () => {
      const token = localStorage.getItem('mindmate_token');
      const userStr = localStorage.getItem('mindmate_user');
      
      if (token && userStr) {
        try {
          const user = JSON.parse(userStr);
          setCurrentUser(user);
        } catch (error) {
          console.error('解析用户信息失败:', error);
          localStorage.removeItem('mindmate_token');
          localStorage.removeItem('mindmate_user');
        }
      }
      setIsCheckingAuth(false);
    };
    
    checkAuth();
  }, []);

  React.useEffect(() => {
    loadAvailableModels();
    if (currentUser) {
      loadSessions();
    }
    loadCustomRoles();
  }, [currentUser]);

  // 监听会话搜索和筛选变化
  React.useEffect(() => {
    setSessionPage(1);
    loadSessions();
  }, [sessionSearchQuery, sessionFilter]);

  // 监听会话分页变化
  React.useEffect(() => {
    if (sessionPage > 1) {
      loadSessions();
    }
  }, [sessionPage]);

  // 消息操作功能
  const copyMessage = async (content: string) => {
    try {
      await navigator.clipboard.writeText(content);
      // 可以添加提示
    } catch (err) {
      console.error('复制失败:', err);
    }
  };

  // 角色切换处理函数
  const handleRoleChange = (newRoleId: string) => {
    if (newRoleId === currentRole) return;
    
    // 检查是否有当前会话且有消息
    if (currentSessionId && messages.length > 0) {
      setPendingRoleId(newRoleId);
      setIsRoleSwitchModalOpen(true);
      setIsRoleSelectorOpen(false);
    } else {
      // 没有活跃会话，直接切换角色
      setCurrentRole(newRoleId);
      setIsRoleSelectorOpen(false);
    }
  };

  // 确认角色切换并创建新会话
  const confirmRoleSwitch = async () => {
    if (!pendingRoleId) return;
    
    setCurrentRole(pendingRoleId);
    
    // 清空当前消息并创建新会话
    setMessages([]);
    setCurrentSessionId(null);
    
    setIsRoleSwitchModalOpen(false);
    setPendingRoleId(null);
  };

  // 取消角色切换
  const cancelRoleSwitch = () => {
    setIsRoleSwitchModalOpen(false);
    setPendingRoleId(null);
  };

  const regenerateMessage = async (messageId: string) => {
    if (regeneratingMessageId) return; // 防止重复点击
    
    setRegeneratingMessageId(messageId);
    
    // 找到要重新生成的消息
    const messageIndex = messages.findIndex(m => m.id === messageId);
    if (messageIndex === -1) return;
    
    // 获取该消息之前的所有消息作为上下文
    const contextMessages = messages.slice(0, messageIndex);
    
    try {
      // 获取当前角色的系统提示词
      const currentRoleInfo = getCurrentRoleInfo();
      const systemPrompt = currentRoleInfo.systemPrompt;
      const apiMessages = [
        { role: 'system', content: systemPrompt },
        ...contextMessages.slice(-6).map(msg => ({
          role: msg.role,
          content: msg.content
        }))
      ];
      
      // 调用API重新生成
      const response = await fetch('/api/chat', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          messages: apiMessages,
          model: currentModel,
          searchEnabled: isSearchEnabled
        })
      });
      
      if (!response.ok) {
        throw new Error(`API请求失败: ${response.status}`);
      }
      
      const data = await response.json();
      
      // 更新消息内容
      setMessages(prev => 
        prev.map(msg => 
          msg.id === messageId 
            ? { ...msg, content: data.content, timestamp: new Date() }
            : msg
        )
      );
      
    } catch (error) {
      console.error('重新生成失败:', error);
    } finally {
      setRegeneratingMessageId(null);
    }
  };

  const toggleMessageActions = (messageId: string) => {
    setMessageActions(prev => ({
      ...prev,
      [messageId]: !prev[messageId]
    }));
  };

  // 点击外部关闭模型选择器
  React.useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (isModelSelectorOpen) {
        const target = event.target as Element;
        if (!target.closest('.model-selector')) {
          setIsModelSelectorOpen(false);
        }
      }
      if (isRoleSelectorOpen) {
        const target = event.target as Element;
        if (!target.closest('.role-selector')) {
          setIsRoleSelectorOpen(false);
        }
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [isModelSelectorOpen, isRoleSelectorOpen]);

  // 发送消息函数 - 集成会话管理
  const handleSendMessage = async () => {
    if (inputValue.trim() && !isLoading) {
      const currentInput = inputValue.trim();
      setInputValue('');
      setIsLoading(true);
      setIsThinking(true);
      setThinkingRole(currentRole);

      // 添加用户消息到UI
      const userMessage = {
        id: Date.now().toString(),
        role: 'user' as const,
        content: currentInput,
        timestamp: new Date()
      };
      setMessages(prev => [...prev, userMessage]);
      
      let sessionId = currentSessionId;
      
      // 如果没有当前会话，先创建一个
      if (!sessionId) {
        try {
          const roleInfo = getCurrentRoleInfo();
          const response = await fetch('/api/sessions', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              title: `与${roleInfo.name}的对话`,
              roleId: currentRole,
              model: currentModel,
              searchEnabled: true
            })
          });
          const result = await response.json();
          
          if (result.success) {
            sessionId = result.data.id;
            setCurrentSessionId(sessionId);
            loadSessions();
          } else {
            console.error('创建会话失败:', result);
            setIsLoading(false);
            setIsThinking(false);
            setThinkingRole(null);
            return;
          }
        } catch (error) {
          console.error('创建会话失败:', error);
          setIsLoading(false);
          setIsThinking(false);
          setThinkingRole(null);
          return;
        }
      }
      
      try {
        // 添加用户消息到会话 (使用sessionId变量)
        await fetch(`/api/sessions/${sessionId}/messages`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            role: 'user',
            content: currentInput
          })
        });
        
        // 获取当前角色的系统提示词
        const currentRoleInfo = getCurrentRoleInfo();
        const systemPrompt = currentRoleInfo.systemPrompt;
        const apiMessages = [
          { role: 'system', content: systemPrompt },
          // 只发送最近的几条消息，避免token过多
          ...messages.slice(-6).map(msg => ({
            role: msg.role,
            content: msg.content
          })),
          { role: 'user', content: currentInput }
        ];
        
        // 调用AI API
        const response = await fetch('/api/chat', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            messages: apiMessages,
            model: currentModel,
            searchEnabled: isSearchEnabled
          })
        });
        
        if (!response.ok) {
          throw new Error(`API请求失败: ${response.status}`);
        }
        
        const data = await response.json();
        const aiContent = data.content;
        
        // 添加AI回复到UI
        const aiMessage = {
          id: (Date.now() + 1).toString(),
          role: 'assistant' as const,
          content: aiContent,
          timestamp: new Date()
        };
        
        setMessages(prev => [...prev, aiMessage]);
        
        // 添加AI回复到会话 (使用sessionId变量)
        await fetch(`/api/sessions/${sessionId}/messages`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            role: 'assistant',
            content: aiContent
          })
        });
        
        // 更新会话预览
        loadSessions();
        
      } catch (error) {
        console.error('AI API调用失败:', error);
        
        // 如果API失败，显示错误消息
        const errorMessage = {
          id: (Date.now() + 1).toString(),
          role: 'assistant' as const,
          content: '抱歉，AI服务暂时不可用。请稍后再试，或检查网络连接。',
          timestamp: new Date()
        };
        
        setMessages(prev => [...prev, errorMessage]);
      } finally {
        setIsLoading(false);
        setIsThinking(false);
        setThinkingRole('');
      }
    }
  };

  // 键盘事件处理
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  // 清空对话
  const handleClearChat = () => {
    const confirmClear = window.confirm('确定要清空所有对话内容吗？此操作不可恢复。');
    if (confirmClear) {
      const welcomeMessage = {
        id: Date.now().toString(),
        role: 'assistant' as const,
        content: `您好！我是${currentRole === 'emma' ? 'Emma，很高兴为您提供心理咨询服务' : currentRole === 'sophie' ? 'Sophie，您的学术研究助手' : 'Mike，您的面试教练'}。有什么我可以帮助您的吗？`,
        timestamp: new Date()
      };
      setMessages([welcomeMessage]);
    }
  };

  // 导出对话
  const handleExportChat = () => {
    const chatText = messages.map(msg => 
      `[${msg.timestamp.toLocaleString()}] ${msg.role === 'user' ? '用户' : 'AI'}: ${msg.content}`
    ).join('\n\n');
    
    const blob = new Blob([chatText], { type: 'text/plain;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `MindMate对话记录_${new Date().toISOString().split('T')[0]}.txt`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  return (
    <div className="h-screen bg-gray-50 flex">
      {/* 左侧会话列表 */}
      <div className={`bg-white border-r transition-all duration-300 flex flex-col ${
        isSessionListOpen ? 'w-80' : 'w-0'
      } ${isSessionListOpen ? '' : 'overflow-hidden'}`}>
        {/* 会话列表头部 */}
        <div className="p-4 border-b">
          <div className="flex items-center justify-between mb-4">
            <h2 className="font-semibold text-gray-900">对话历史</h2>
            <button
              onClick={createNewSession}
              className="px-3 py-1.5 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors text-sm"
            >
              ＋ 新对话
            </button>
          </div>
          
          {/* 搜索框 */}
          <div className="relative mb-3">
            <input
              type="text"
              placeholder="搜索对话..."
              value={sessionSearchQuery}
              onChange={(e) => setSessionSearchQuery(e.target.value)}
              className="w-full pl-10 pr-3 py-2.5 bg-gray-50 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-400 focus:bg-white focus:border-blue-400 transition-all duration-200 placeholder-gray-500"
            />
            <div className="absolute left-3 top-3 text-gray-400">
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
              </svg>
            </div>
          </div>
          
          {/* 筛选器 */}
          <div className="flex gap-1">
            <button
              onClick={() => setSessionFilter('')}
              className={`px-2 py-1 text-xs rounded ${
                sessionFilter === '' ? 'bg-blue-100 text-blue-700' : 'text-gray-600 hover:bg-gray-100'
              }`}
            >
              全部
            </button>
            <button
              onClick={() => setSessionFilter('favorite')}
              className={`px-2 py-1 text-xs rounded ${
                sessionFilter === 'favorite' ? 'bg-blue-100 text-blue-700' : 'text-gray-600 hover:bg-gray-100'
              }`}
            >
              收藏
            </button>
            <button
              onClick={() => setSessionFilter('archived')}
              className={`px-2 py-1 text-xs rounded ${
                sessionFilter === 'archived' ? 'bg-blue-100 text-blue-700' : 'text-gray-600 hover:bg-gray-100'
              }`}
            >
              归档
            </button>
          </div>
        </div>
        
        {/* 会话列表 */}
        <div className="flex-1 overflow-y-auto">
          {isLoadingSessions ? (
            <div className="p-4 text-center text-gray-500">
              <div className="animate-spin w-4 h-4 border-2 border-blue-500 border-t-transparent rounded-full mx-auto mb-2"></div>
              加载中...
            </div>
          ) : sessions.length === 0 ? (
            <div className="p-4 text-center text-gray-500">
              <p>暂无对话</p>
              <button
                onClick={createNewSession}
                className="mt-2 text-blue-500 hover:text-blue-600 text-sm"
              >
                开始新对话
              </button>
            </div>
          ) : (
            <div className="p-3 space-y-2">
              {sessions.map((session) => {
                // 获取角色配置（支持预设和自定义角色）
                const roleConfig = getRoleInfo(session.roleId);
                
                // 生成会话标题：优先显示最后一条用户消息，否则显示默认标题
                const getSessionDisplayTitle = () => {
                  if (session.lastMessagePreview && session.lastMessagePreview.trim()) {
                    // 截取前20个字符作为标题
                    return session.lastMessagePreview.length > 20 
                      ? session.lastMessagePreview.substring(0, 20) + '...'
                      : session.lastMessagePreview;
                  }
                  return `与${roleConfig.name}的对话`;
                };

                return (
                  <div
                    key={session.id}
                    onClick={() => switchToSession(session.id)}
                    className={`relative p-4 rounded-xl cursor-pointer transition-all duration-200 group border ${
                      currentSessionId === session.id
                        ? 'bg-gradient-to-r from-blue-50 to-indigo-50 border-blue-200 shadow-sm'
                        : 'bg-white hover:bg-gray-50 border-gray-100 hover:border-gray-200 hover:shadow-sm'
                    }`}
                  >
                    {/* 角色标识角标 */}
                    <div className={`absolute -top-1 -right-1 w-8 h-8 rounded-full flex items-center justify-center text-sm border-2 border-white shadow-sm ${
                      roleConfig.color === 'purple' ? 'bg-purple-100 text-purple-600' :
                      roleConfig.color === 'indigo' ? 'bg-indigo-100 text-indigo-600' :
                      'bg-emerald-100 text-emerald-600'
                    }`}>
                      {roleConfig.icon}
                    </div>

                    <div className="flex items-start justify-between pr-6">
                      <div className="flex-1 min-w-0">
                        {/* 会话标题 */}
                        <div className="flex items-start gap-2 mb-2">
                          <h4 className="font-medium text-sm text-gray-900 line-clamp-2 leading-5">
                            {getSessionDisplayTitle()}
                          </h4>
                          {session.isFavorite && (
                            <span className="text-yellow-500 text-sm flex-shrink-0">⭐</span>
                          )}
                        </div>
                        
                        {/* 角色标识和时间 */}
                        <div className="flex items-center justify-between">
                          <div className="flex items-center gap-2">
                            <div className={`inline-flex items-center gap-1.5 px-2 py-1 rounded-full text-xs font-medium ${
                              roleConfig.color === 'purple' ? 'bg-purple-50 text-purple-700' :
                              roleConfig.color === 'indigo' ? 'bg-indigo-50 text-indigo-700' :
                              'bg-emerald-50 text-emerald-700'
                            }`}>
                              <span className="text-xs">{roleConfig.icon}</span>
                              <span>{roleConfig.name}</span>
                            </div>
                            
                            {/* 备忘录标签 */}
                            <button
                              onClick={(e) => {
                                e.stopPropagation();
                                setMemoModal({
                                  isOpen: true,
                                  sessionId: session.id,
                                  sessionTitle: getSessionDisplayTitle()
                                });
                              }}
                              className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs bg-orange-50 text-orange-600 hover:bg-orange-100 transition-colors"
                              title="查看/编辑备忘录"
                            >
                              <svg className="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
                                <path d="M4 4a2 2 0 00-2 2v8a2 2 0 002 2h12a2 2 0 002-2V6a2 2 0 00-2-2H4zm0 2h12v8H4V6z"/>
                                <path d="M6 8h8v2H6V8zm0 3h6v2H6v-2z"/>
                              </svg>
                              <span>备忘录</span>
                            </button>
                          </div>
                          
                          <span className="text-xs text-gray-400">
                            {new Date(session.lastActiveAt).toLocaleString('zh-CN', {
                              month: 'short',
                              day: 'numeric',
                              hour: '2-digit',
                              minute: '2-digit'
                            })}
                          </span>
                        </div>
                      </div>
                    </div>
                    
                    {/* 悬停操作菜单 */}
                    <div className="absolute top-3 right-3 opacity-0 group-hover:opacity-100 transition-opacity">
                      <div className="flex gap-1">
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            toggleFavoriteSession(session.id);
                          }}
                          className={`p-1.5 rounded-lg text-xs transition-colors ${
                            session.isFavorite
                              ? 'text-yellow-500 hover:bg-yellow-50'
                              : 'text-gray-400 hover:bg-gray-100 hover:text-gray-600'
                          }`}
                          title={session.isFavorite ? '取消收藏' : '收藏'}
                        >
                          <svg className="w-3 h-3" fill="currentColor" viewBox="0 0 24 24">
                            <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/>
                          </svg>
                        </button>
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            const newTitle = prompt('重命名对话', getSessionDisplayTitle());
                            if (newTitle && newTitle !== session.title) {
                              renameSession(session.id, newTitle);
                            }
                          }}
                          className="p-1.5 rounded-lg text-xs text-gray-400 hover:bg-gray-100 hover:text-gray-600 transition-colors"
                          title="重命名"
                        >
                          <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                          </svg>
                        </button>
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            setConfirmModal({
                              isOpen: true,
                              title: '删除会话',
                              message: `确定要删除会话 "${session.title}" 吗？\n\n删除后会话将被归档，您可以稍后从归档中恢复。`,
                              onConfirm: () => {
                                deleteSession(session.id);
                                setConfirmModal(prev => ({ ...prev, isOpen: false }));
                              },
                              sessionTitle: session.title
                            });
                          }}
                          className="p-1.5 rounded-lg text-xs text-gray-400 hover:bg-red-50 hover:text-red-500 transition-colors"
                          title="删除"
                        >
                          <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                          </svg>
                        </button>
                      </div>
                    </div>
                  </div>
                );
              })}
              
              {/* 加载更多 */}
              {sessionPage < sessionPagination.totalPages && (
                <button
                  onClick={() => setSessionPage(prev => prev + 1)}
                  className="w-full p-2 text-sm text-gray-500 hover:text-gray-700 hover:bg-gray-50 rounded"
                >
                  加载更多...
                </button>
              )}
            </div>
          )}
        </div>
        
        {/* 底部状态栏 */}
        <div className="p-3 border-t bg-gray-50">
          <div className="flex justify-between items-center text-xs text-gray-500">
            <span>共 {sessionPagination.total} 个对话</span>
            <button
              onClick={() => setIsSessionListOpen(false)}
              className="text-gray-400 hover:text-gray-600"
              title="收起"
            >
              ←
            </button>
          </div>
        </div>
      </div>
      
      {/* 中间对话区域 */}
      <div className="flex-1 flex flex-col">
        {/* 顶部工具栏 - 基于设计方案 */}
        <div className="bg-white border-b p-4 flex items-center justify-between">
          {/* 左侧：会话列表切换 + 品牌 */}
          <div className="flex items-center gap-4">
            {!isSessionListOpen && (
              <button
                onClick={() => setIsSessionListOpen(true)}
                className="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition-colors"
                title="显示对话列表"
              >
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
                </svg>
              </button>
            )}
            <h1 className="text-xl font-bold text-blue-600">🧠 MindMate</h1>
          </div>
          
          {/* 中间：角色和模型选择器 */}
          <div className="flex items-center gap-4">
            {/* 角色选择器 */}
            <div className="relative role-selector">
              <button
                onClick={() => setIsRoleSelectorOpen(!isRoleSelectorOpen)}
                className="flex items-center gap-3 px-4 py-2.5 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors min-w-52"
              >
                <div className="flex items-center gap-2 flex-1">
                  <span className="text-base">
                    {getCurrentRoleInfo().icon}
                  </span>
                  <div className="text-left">
                    <div className="text-sm font-medium text-gray-900">
                      {getCurrentRoleInfo().name} - {getCurrentRoleInfo().title}
                    </div>
                    <div className="text-xs text-gray-500 truncate max-w-32">
                      {getCurrentRoleInfo().features?.[0] || ''}
                    </div>
                  </div>
                </div>
                
                <div className="flex items-center gap-2">
                  <span className="px-2 py-0.5 bg-green-100 text-green-700 text-xs rounded font-medium">活跃</span>
                  <svg className={`w-4 h-4 transition-transform ${isRoleSelectorOpen ? 'rotate-180' : ''}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                  </svg>
                </div>
              </button>
              
              {/* 角色选择下拉菜单 */}
              {isRoleSelectorOpen && (
                <div className="absolute top-full left-0 mt-1 w-80 bg-white border border-gray-300 rounded-lg shadow-lg z-50">
                  <div className="p-4 border-b bg-gray-50">
                    <h3 className="font-medium text-sm text-gray-900">选择AI角色</h3>
                    <p className="text-xs text-gray-600 mt-1">选择不同的专业角色以获得个性化的对话体验</p>
                  </div>
                  
                  <div className="max-h-80 overflow-y-auto">
                    {/* 预设角色 */}
                    <div className="border-b border-gray-100 pb-2">
                      <div className="px-4 py-2 bg-gray-50">
                        <h4 className="font-medium text-xs text-gray-700">预设角色</h4>
                      </div>
                      {roleConfigs.map((role) => (
                        <button
                          key={role.id}
                          onClick={() => handleRoleChange(role.id)}
                          className={`w-full p-3 text-left hover:bg-gray-50 transition-colors ${
                            currentRole === role.id ? 'bg-blue-50 border-r-2 border-blue-500' : ''
                          }`}
                        >
                          <div className="flex items-start justify-between">
                            <div className="flex items-start gap-3 flex-1">
                              <span className="text-lg">{role.icon}</span>
                              <div className="flex-1">
                                <div className="font-medium text-sm text-gray-900">{role.name} - {role.title}</div>
                              <div className="text-xs text-gray-500 mt-0.5 leading-normal line-clamp-1">{role.description}</div>
                            </div>
                          </div>
                          <div className="flex flex-col items-end gap-1 ml-2">
                            <span className="px-2 py-0.5 text-xs rounded font-medium bg-green-100 text-green-700">
                              活跃
                            </span>
                            {currentRole === role.id && (
                              <span className="text-xs text-blue-600 font-medium">✓ 当前角色</span>
                            )}
                          </div>
                        </div>
                        
                        {/* 角色特性标签 */}
                        <div className="flex flex-wrap gap-1 mt-2 ml-7">
                          {role.features?.slice(0, 3).map((feature: string) => (
                            <span key={feature} className="px-2 py-0.5 bg-gray-100 text-gray-600 text-xs rounded-full">
                              {feature}
                            </span>
                          ))}
                        </div>
                      </button>
                    ))}
                    </div>
                    
                    {/* 自定义角色 */}
                    {customRoles.length > 0 && (
                      <div className="border-b border-gray-100 pb-2">
                        <div className="px-4 py-2 bg-gray-50">
                          <h4 className="font-medium text-xs text-gray-700">我的角色</h4>
                        </div>
                        {customRoles.map((role) => (
                          <div key={role.id} className={`p-3 hover:bg-gray-50 transition-colors ${
                            currentRole === role.id ? 'bg-blue-50 border-r-2 border-blue-500' : ''
                          }`}>
                            <div className="flex items-start justify-between">
                              <button
                                onClick={() => handleRoleChange(role.id)}
                                className="flex items-start gap-3 flex-1 text-left"
                              >
                                <span className="text-lg">🎭</span>
                                <div className="flex-1">
                                  <div className="font-medium text-sm text-gray-900">{role.name}</div>
                                  <div className="text-xs text-gray-500 mt-0.5 line-clamp-1">
                                    输入：{role.input_spec.length > 25 ? role.input_spec.substring(0, 25) + '...' : role.input_spec}
                                  </div>
                                  <div className="text-xs text-gray-500 line-clamp-1">
                                    输出：{role.output_spec.length > 25 ? role.output_spec.substring(0, 25) + '...' : role.output_spec}
                                  </div>
                                </div>
                              </button>
                              <div className="flex items-center gap-1 ml-2">
                                <button
                                  onClick={(e) => {
                                    e.stopPropagation();
                                    openRoleEditor(role);
                                  }}
                                  className="p-1 hover:bg-gray-200 rounded transition-colors"
                                  title="编辑角色"
                                >
                                  <svg className="w-3 h-3 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                                  </svg>
                                </button>
                                <button
                                  onClick={(e) => {
                                    e.stopPropagation();
                                    if (confirm(`确定删除角色"${role.name}"吗？`)) {
                                      deleteCustomRole(role.id);
                                    }
                                  }}
                                  className="p-1 hover:bg-red-100 rounded transition-colors"
                                  title="删除角色"
                                >
                                  <svg className="w-3 h-3 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                  </svg>
                                </button>
                              </div>
                            </div>
                          </div>
                        ))}
                      </div>
                    )}
                    
                    {/* 创建角色按钮 */}
                    <div className="p-4 border-t border-gray-100">
                      <button
                        onClick={() => {
                          openRoleEditor(null);
                          setIsRoleSelectorOpen(false);
                        }}
                        className="w-full flex items-center gap-2 px-3 py-2 border-2 border-dashed border-gray-300 rounded-lg hover:border-blue-400 hover:bg-blue-50 transition-all text-gray-600 hover:text-blue-600"
                      >
                        <span className="text-base">➕</span>
                        <span className="font-medium text-sm">创建自定义角色</span>
                      </button>
                    </div>
                  </div>
                  
                  <div className="p-3 bg-gray-50 rounded-b-lg">
                    <div className="flex justify-between items-center">
                      <span className="text-xs text-gray-500">
                        共 {roleConfigs.length + customRoles.length} 个角色
                      </span>
                      <span className="text-xs text-gray-400">
                        点击切换角色
                      </span>
                    </div>
                  </div>
                </div>
              )}
            </div>
            
            {/* 动态模型选择器 */}
            <div className="relative model-selector">
              <button
                onClick={() => setIsModelSelectorOpen(!isModelSelectorOpen)}
                className="flex items-center gap-3 px-4 py-2.5 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors min-w-52"
              >
                {isLoadingModels ? (
                  <span className="text-sm font-medium">🔄 加载中...</span>
                ) : (
                  <>
                    <div className="flex items-center gap-2 flex-1">
                      <span className="text-base">
                        {availableModels.find(m => m.id === currentModel)?.icon || '🤖'} 
                      </span>
                      <div className="text-left">
                        <div className="text-sm font-medium text-gray-900">
                          {availableModels.find(m => m.id === currentModel)?.name || (availableModels.length > 0 ? '未知模型' : '加载中...')}
                        </div>
                        <div className="text-xs text-gray-500 truncate max-w-32">
                          {availableModels.find(m => m.id === currentModel)?.provider || ''}
                        </div>
                      </div>
                    </div>
                    
                    <div className="flex items-center gap-2">
                      {availableModels.find(m => m.id === currentModel)?.status === 'available' && (
                        <span className="px-2 py-0.5 bg-green-100 text-green-700 text-xs rounded font-medium">可用</span>
                      )}
                      <svg className={`w-4 h-4 transition-transform ${isModelSelectorOpen ? 'rotate-180' : ''}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                      </svg>
                    </div>
                  </>
                )}
              </button>
              
              {/* 模型选择下拉菜单 */}
              {isModelSelectorOpen && (
                <div className="absolute top-full left-0 mt-1 w-80 bg-white border border-gray-300 rounded-lg shadow-lg z-50">
                  <div className="p-4 border-b bg-gray-50">
                    <h3 className="font-medium text-sm text-gray-900">选择AI模型</h3>
                    <p className="text-xs text-gray-600 mt-1">选择不同的模型以获得不同的对话体验</p>
                  </div>
                  
                  <div className="max-h-64 overflow-y-auto">
                    {availableModels.map((model) => (
                      <button
                        key={model.id}
                        onClick={() => {
                          switchModel(model.id);
                          setIsModelSelectorOpen(false);
                        }}
                        className={`w-full p-4 text-left hover:bg-gray-50 transition-colors ${
                          currentModel === model.id ? 'bg-blue-50 border-r-2 border-blue-500' : ''
                        }`}
                      >
                        <div className="flex items-start justify-between">
                          <div className="flex items-start gap-3 flex-1">
                            <span className="text-lg">{model.icon}</span>
                            <div className="flex-1">
                              <div className="font-medium text-sm text-gray-900">{model.name}</div>
                              <div className="text-xs text-gray-500 mt-0.5 leading-relaxed">{model.description}</div>
                            </div>
                          </div>
                          <div className="flex flex-col items-end gap-1 ml-2">
                            <span className={`px-2 py-0.5 text-xs rounded font-medium ${
                              model.status === 'available' 
                                ? 'bg-green-100 text-green-700' 
                                : 'bg-yellow-100 text-yellow-700'
                            }`}>
                              {model.status === 'available' ? '可用' : '需配置'}
                            </span>
                            {currentModel === model.id && (
                              <span className="text-xs text-blue-600 font-medium">✓ 当前使用</span>
                            )}
                          </div>
                        </div>
                        
                        {/* 模型特性标签 */}
                        <div className="flex flex-wrap gap-1 mt-3 ml-7">
                          {model.features?.slice(0, 3).map((feature: string) => (
                            <span key={feature} className="px-2 py-1 bg-gray-100 text-gray-600 text-xs rounded-full">
                              {feature}
                            </span>
                          ))}
                        </div>
                      </button>
                    ))}
                  </div>
                  
                  <div className="p-3 border-t bg-gray-50">
                    <div className="flex justify-between items-center">
                      <span className="text-xs text-gray-500">
                        共 {availableModels.length} 个模型可用
                      </span>
                      <button 
                        onClick={() => setIsModelSelectorOpen(false)}
                        className="text-sm text-gray-600 hover:text-gray-800 px-2 py-1 rounded hover:bg-gray-100 transition-colors"
                      >
                        关闭
                      </button>
                    </div>
                  </div>
                </div>
              )}
            </div>
          </div>
          
          {/* 右侧：状态和用户信息 */}
          <div className="flex items-center gap-3">
            {/* 微型对话信息 */}
            <div className="flex items-center gap-2 px-3 py-1.5 bg-gray-50 rounded-lg">
              <div className="flex items-center gap-1.5 text-xs text-gray-600">
                <span>💬</span>
                <span>{messages.length}</span>
              </div>
              <div className="w-px h-3 bg-gray-300"></div>
              <div className="text-xs text-gray-500">
                {currentRole === 'emma' ? '🧠 心理' : currentRole === 'sophie' ? '📖 学术' : '💼 职场'}
              </div>
            </div>
            
            <button className="p-2 rounded-md hover:bg-gray-100 transition-colors">⚙️</button>
            
            {/* 用户信息或登录按钮 */}
            {currentUser ? (
              <div className="flex items-center gap-2">
                <div className="w-8 h-8 bg-gradient-to-r from-blue-500 to-purple-500 rounded-full flex items-center justify-center text-white font-medium text-sm">
                  {currentUser.username?.[0]?.toUpperCase() || 'U'}
                </div>
                <button
                  onClick={handleLogout}
                  className="text-sm text-gray-600 hover:text-gray-900"
                  title="登出"
                >
                  登出
                </button>
              </div>
            ) : (
              <button
                onClick={() => setShowLoginDialog(true)}
                className="px-3 py-1.5 bg-gradient-to-r from-blue-600 to-purple-600 text-white rounded-lg hover:from-blue-700 hover:to-purple-700 transition-all duration-200 font-medium text-sm"
              >
                登录
              </button>
            )}
          </div>
        </div>
        
        
        {/* 对话内容区域 */}
        <div className="flex-1 p-6 overflow-y-auto">
          <div className="max-w-4xl mx-auto space-y-4">
            
            {/* 对话轮次警告条 */}
            {showTurnWarning && (
              <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4 mb-4">
                <div className="flex items-center gap-3">
                  <span className="text-yellow-600 text-xl">⚠️</span>
                  <div className="flex-1">
                    <h4 className="text-yellow-800 font-semibold">对话轮次较多提醒</h4>
                    <p className="text-yellow-700 text-sm mt-1">
                      当前对话已进行 {conversationTurns} 轮，接近系统阈值。建议查看或生成备忘录以优化对话体验。
                    </p>
                  </div>
                  <button
                    onClick={() => setIsMemoDialogOpen(true)}
                    className="px-3 py-1.5 bg-yellow-200 text-yellow-800 rounded-md hover:bg-yellow-300 transition-colors text-sm"
                  >
                    管理备忘录
                  </button>
                  <button
                    onClick={() => setShowTurnWarning(false)}
                    className="text-yellow-600 hover:text-yellow-800 transition-colors"
                  >
                    ✕
                  </button>
                </div>
              </div>
            )}

            {/* 备忘录状态条 */}
            {currentMemo && conversationTurns >= 5 && (
              <div className="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-4">
                <div className="flex items-center gap-3">
                  <span className="text-blue-600 text-xl">📝</span>
                  <div className="flex-1">
                    <h4 className="text-blue-800 font-semibold">对话备忘录已生成</h4>
                    <p className="text-blue-700 text-sm mt-1">
                      系统已为此对话生成备忘录，点击查看或编辑。生成时间：{memoCreatedAt ? new Date(memoCreatedAt).toLocaleString() : ''}
                    </p>
                  </div>
                  <button
                    onClick={() => setIsMemoDialogOpen(true)}
                    className="px-3 py-1.5 bg-blue-200 text-blue-800 rounded-md hover:bg-blue-300 transition-colors text-sm"
                  >
                    查看备忘录
                  </button>
                </div>
              </div>
            )}

            {messages.map((message) => (
              <div key={message.id} className={`group mb-4 ${message.role === 'user' ? 'flex justify-end' : 'flex justify-start'}`}>
                {message.role === 'assistant' ? (
                  <div className="max-w-2xl w-full">
                    {/* AI消息头部 */}
                    <div className="flex items-center gap-2 mb-2">
                      <span className="text-base">
                        {currentRole === 'emma' && '👩‍⚕️'}
                        {currentRole === 'sophie' && '👩‍🎓'}
                        {currentRole === 'mike' && '👨‍💼'}
                      </span>
                      {isSearchEnabled && (
                        <span className="text-xs bg-blue-100 text-blue-700 px-2 py-1 rounded-full flex items-center gap-1">
                          🔍 搜索增强
                        </span>
                      )}
                      <span className="text-sm font-medium text-gray-900">
                        {currentRole === 'emma' && 'Emma'}
                        {currentRole === 'sophie' && 'Sophie'}
                        {currentRole === 'mike' && 'Mike'}
                      </span>
                      <span className="text-xs text-gray-500">
                        {message.timestamp.toLocaleTimeString()}
                      </span>
                    </div>
                    
                    {/* AI消息内容 */}
                    <div className="bg-gray-50 border border-gray-200 rounded-2xl p-4 shadow-sm hover:shadow-md transition-shadow">
                      <div 
                        className="text-gray-800 leading-relaxed whitespace-pre-line"
                        dangerouslySetInnerHTML={{ __html: parseMarkdown(message.content) }}
                      />
                    </div>
                    
                    {/* AI消息操作按钮 */}
                    <div className={`flex items-center gap-2 mt-2 transition-opacity ${
                      messageActions[message.id] ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
                    }`}>
                      <button
                        onClick={() => copyMessage(message.content)}
                        className="flex items-center gap-1 px-2 py-1 text-xs text-gray-600 hover:text-blue-600 hover:bg-blue-50 rounded transition-colors"
                        title="复制消息"
                      >
                        📋 复制
                      </button>
                      <button
                        onClick={() => regenerateMessage(message.id)}
                        disabled={regeneratingMessageId === message.id}
                        className="flex items-center gap-1 px-2 py-1 text-xs text-gray-600 hover:text-green-600 hover:bg-green-50 rounded transition-colors disabled:opacity-50"
                        title="重新生成"
                      >
                        {regeneratingMessageId === message.id ? '🔄' : '🔄'} 
                        {regeneratingMessageId === message.id ? '重生成中...' : '重新生成'}
                      </button>
                      <button
                        onClick={() => {/* TODO: 实现点赞功能 */}}
                        className="flex items-center gap-1 px-2 py-1 text-xs text-gray-600 hover:text-green-600 hover:bg-green-50 rounded transition-colors"
                        title="好评"
                      >
                        👍
                      </button>
                      <button
                        onClick={() => {/* TODO: 实现点踩功能 */}}
                        className="flex items-center gap-1 px-2 py-1 text-xs text-gray-600 hover:text-red-600 hover:bg-red-50 rounded transition-colors"
                        title="差评"
                      >
                        👎
                      </button>
                    </div>
                  </div>
                ) : (
                  <div className="max-w-2xl">
                    {/* 用户消息 */}
                    <div className="relative group">
                      {editingMessageId === message.id ? (
                        /* 编辑模式 */
                        <div className="bg-white border-2 border-blue-300 rounded-2xl p-3 shadow-md">
                          <textarea
                            className="w-full resize-none border-none outline-none text-gray-800 leading-relaxed placeholder-gray-400 bg-transparent"
                            value={editingContent}
                            onChange={(e) => setEditingContent(e.target.value)}
                            onKeyDown={handleEditKeyDown}
                            placeholder="输入消息内容..."
                            rows={Math.max(2, editingContent.split('\n').length)}
                            autoFocus
                          />
                          <div className="flex items-center justify-end gap-2 mt-2 pt-2 border-t border-gray-200">
                            <button 
                              onClick={handleEditSubmit}
                              className="flex items-center gap-1 px-3 py-1.5 bg-blue-600 text-white text-sm rounded-lg hover:bg-blue-700 transition-colors"
                            >
                              ✓ 保存
                            </button>
                            <button 
                              onClick={cancelEdit}
                              className="flex items-center gap-1 px-3 py-1.5 bg-gray-100 text-gray-600 text-sm rounded-lg hover:bg-gray-200 transition-colors"
                            >
                              ✕ 取消
                            </button>
                          </div>
                        </div>
                      ) : (
                        /* 显示模式 */
                        <div className="relative">
                          <div className="bg-gradient-to-r from-blue-600 to-blue-700 text-white rounded-2xl px-4 py-3 shadow-sm">
                            <p className="leading-relaxed whitespace-pre-line">{message.content}</p>
                            {(message as any).edited && (
                              <span className="inline-block mt-1 text-xs bg-blue-500 bg-opacity-30 px-2 py-0.5 rounded" 
                                    title={`编辑于 ${(message as any).edited_at ? new Date((message as any).edited_at).toLocaleString() : ''}`}>
                                (已编辑)
                              </span>
                            )}
                          </div>
                          
                          {/* 编辑按钮 - 只在有会话时显示 */}
                          {currentSessionId && (
                            <button
                              className="absolute -right-2 -top-2 opacity-0 group-hover:opacity-100 transition-opacity bg-white border border-gray-300 rounded-full p-1.5 shadow-sm hover:shadow-md hover:bg-gray-50"
                              onClick={() => startEditMessage(message)}
                              title="编辑消息"
                            >
                              <span className="text-sm">✏️</span>
                            </button>
                          )}
                          
                          <div className="text-xs text-gray-500 text-right mt-1">
                            {message.timestamp.toLocaleTimeString()}
                          </div>
                        </div>
                      )}
                    </div>
                  </div>
                )}
              </div>
            ))}
            
            {/* 角色思考状态指示器 */}
            {isThinking && (() => {
              const thinkingRoleInfo = getRoleInfo(thinkingRole);
              return (
                <div className="group mb-4 flex justify-start" role="status" aria-live="polite">
                  <div className="max-w-2xl w-full">
                    {/* 思考状态头部 */}
                    <div className="flex items-center gap-2 mb-2">
                      <span className="text-base">
                        {thinkingRoleInfo.icon || '🤖'}
                      </span>
                      <span className="text-sm font-medium text-gray-900">
                        {thinkingRoleInfo.name || 'AI助手'}
                      </span>
                      <span className="text-xs text-gray-500">正在思考...</span>
                    </div>
                    
                    {/* 思考状态内容 */}
                    <div className="bg-gray-50 border border-gray-200 rounded-2xl p-4 shadow-sm">
                      <div className="flex items-center gap-3">
                        <div className="flex gap-1">
                          <div className="w-2 h-2 bg-blue-400 rounded-full animate-bounce"></div>
                          <div className="w-2 h-2 bg-blue-400 rounded-full animate-bounce" style={{animationDelay: '0.1s'}}></div>
                          <div className="w-2 h-2 bg-blue-400 rounded-full animate-bounce" style={{animationDelay: '0.2s'}}></div>
                        </div>
                        <span className="text-sm text-gray-600">
                          💭 {thinkingRoleInfo.name}
                          {thinkingRoleInfo.title && `（${thinkingRoleInfo.title}）`}正在思考...
                        </span>
                      </div>
                    </div>
                  </div>
                </div>
              );
            })()}
          </div>
        </div>
        
        {/* 现代化输入区域 */}
        <div className="bg-gradient-to-t from-white to-gray-50/30 border-t border-gray-100">
          {/* 智能建议浮动栏 */}
          {!isLoading && inputValue.length === 0 && (
            <div className="px-6 py-2">
              <div className="max-w-4xl mx-auto">
                <div className="flex flex-wrap gap-2">
                  {currentRole === 'emma' && (
                    <>
                      <button onClick={() => setInputValue('我感到有些焦虑，能帮我分析一下原因吗？')} className="inline-flex items-center gap-2 px-3 py-2 bg-white border border-blue-200 text-blue-700 text-sm rounded-full hover:bg-blue-50 hover:border-blue-300 transition-all shadow-sm hover:shadow-md">
                        💙 我感到焦虑
                      </button>
                      <button onClick={() => setInputValue('我需要一些压力管理的建议')} className="inline-flex items-center gap-2 px-3 py-2 bg-white border border-green-200 text-green-700 text-sm rounded-full hover:bg-green-50 hover:border-green-300 transition-all shadow-sm hover:shadow-md">
                        🌱 需要建议
                      </button>
                      <button onClick={() => setInputValue('我想分享一些好消息')} className="inline-flex items-center gap-2 px-3 py-2 bg-white border border-yellow-200 text-yellow-700 text-sm rounded-full hover:bg-yellow-50 hover:border-yellow-300 transition-all shadow-sm hover:shadow-md">
                        😊 分享好消息
                      </button>
                    </>
                  )}
                  {currentRole === 'sophie' && (
                    <>
                      <button onClick={() => setInputValue('我需要帮助理解这个概念')} className="inline-flex items-center gap-2 px-3 py-2 bg-white border border-purple-200 text-purple-700 text-sm rounded-full hover:bg-purple-50 hover:border-purple-300 transition-all shadow-sm hover:shadow-md">
                        🎓 理解概念
                      </button>
                      <button onClick={() => setInputValue('能推荐相关的学术资源吗？')} className="inline-flex items-center gap-2 px-3 py-2 bg-white border border-blue-200 text-blue-700 text-sm rounded-full hover:bg-blue-50 hover:border-blue-300 transition-all shadow-sm hover:shadow-md">
                        📚 推荐资源
                      </button>
                      <button onClick={() => setInputValue('帮我分析这个研究问题')} className="inline-flex items-center gap-2 px-3 py-2 bg-white border border-green-200 text-green-700 text-sm rounded-full hover:bg-green-50 hover:border-green-300 transition-all shadow-sm hover:shadow-md">
                        🔍 研究分析
                      </button>
                    </>
                  )}
                  {currentRole === 'mike' && (
                    <>
                      <button onClick={() => setInputValue('我想准备面试，有什么建议？')} className="inline-flex items-center gap-2 px-3 py-2 bg-white border border-orange-200 text-orange-700 text-sm rounded-full hover:bg-orange-50 hover:border-orange-300 transition-all shadow-sm hover:shadow-md">
                        💼 面试准备
                      </button>
                      <button onClick={() => setInputValue('能帮我优化简历吗？')} className="inline-flex items-center gap-2 px-3 py-2 bg-white border border-blue-200 text-blue-700 text-sm rounded-full hover:bg-blue-50 hover:border-blue-300 transition-all shadow-sm hover:shadow-md">
                        📄 简历优化
                      </button>
                      <button onClick={() => setInputValue('职业发展规划建议')} className="inline-flex items-center gap-2 px-3 py-2 bg-white border border-green-200 text-green-700 text-sm rounded-full hover:bg-green-50 hover:border-green-300 transition-all shadow-sm hover:shadow-md">
                        🚀 职业规划
                      </button>
                    </>
                  )}
                </div>
              </div>
            </div>
          )}
          
          {/* 主输入容器 - 简洁浮动设计 */}
          <div className="px-6 pb-6 pt-2">
            <div className="max-w-4xl mx-auto">
              <div className="bg-white rounded-2xl shadow-lg border border-gray-200/60 overflow-hidden backdrop-blur-sm">
                {/* 搜索设置栏 */}
                <div className="px-5 pt-4 pb-2 border-b border-gray-100">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                      <div className="flex items-center gap-2">
                        <label className="flex items-center cursor-pointer">
                          <div className="relative">
                            <input
                              type="checkbox"
                              checked={isSearchEnabled}
                              onChange={(e) => toggleSearchEnabled(e.target.checked)}
                              className="sr-only"
                            />
                            <div className={`w-10 h-6 rounded-full transition-colors ${
                              isSearchEnabled ? 'bg-blue-500' : 'bg-gray-300'
                            }`}>
                              <div className={`w-4 h-4 bg-white rounded-full shadow-sm transition-transform transform ${
                                isSearchEnabled ? 'translate-x-5' : 'translate-x-1'
                              } mt-1`}></div>
                            </div>
                          </div>
                          <span className="ml-2 text-sm text-gray-700">联网搜索</span>
                        </label>
                        {isSearchEnabled && (
                          <span className="text-xs text-green-600 bg-green-50 px-2 py-1 rounded-full">已启用</span>
                        )}
                      </div>
                    </div>
                    <div className="text-xs text-gray-500">
                      {isSearchEnabled ? '将为您的问题搜索最新信息' : '仅基于模型知识回答'}
                    </div>
                  </div>
                </div>
                {/* 输入框容器 */}
                <div className="flex items-end gap-4 p-5">
                  {/* 主输入框 */}
                  <div className="flex-1 relative">
                    <textarea
                      value={inputValue}
                      onChange={(e) => setInputValue(e.target.value)}
                      onKeyDown={(e) => {
                        if (e.key === 'Enter' && !e.shiftKey) {
                          e.preventDefault();
                          handleSendMessage();
                        }
                      }}
                      placeholder={`与${currentRole === 'emma' ? 'Emma' : currentRole === 'sophie' ? 'Sophie' : 'Mike'}开始对话...`}
                      disabled={isLoading}
                      rows={1}
                      className="w-full px-0 py-3 border-0 focus:outline-none resize-none text-gray-800 placeholder-gray-400 bg-transparent text-[15px] leading-relaxed"
                      style={{
                        minHeight: '28px',
                        maxHeight: '120px',
                        overflowY: inputValue.split('\n').length > 4 ? 'auto' : 'hidden'
                      }}
                    />
                    
                    {/* 微妙的底边线 */}
                    <div className={`absolute bottom-0 left-0 h-0.5 bg-gradient-to-r from-blue-500 to-purple-500 transition-all duration-300 ${
                      inputValue.length > 0 ? 'w-full opacity-100' : 'w-0 opacity-0'
                    }`}></div>
                  </div>
                  
                  {/* 发送按钮 */}
                  <button 
                    onClick={handleSendMessage}
                    disabled={!inputValue.trim() || isLoading}
                    className={`p-3.5 rounded-xl transition-all duration-200 ${
                      inputValue.trim() && !isLoading
                        ? 'bg-gradient-to-r from-blue-500 to-blue-600 text-white shadow-lg hover:shadow-xl hover:scale-105 active:scale-95'
                        : 'bg-gray-100 text-gray-400 cursor-not-allowed'
                    }`}
                  >
                    {isLoading ? (
                      <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                    ) : (
                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
                      </svg>
                    )}
                  </button>
                </div>
                
                {/* 功能按钮栏 - 移到输入框下方 */}
                <div className="flex items-center justify-between px-5 py-3 bg-gray-50/50 border-t border-gray-100">
                  <div className="flex items-center gap-2">
                    {/* 附件和图片按钮 */}
                    <button className="p-2 text-gray-400 hover:text-blue-500 hover:bg-blue-50 rounded-lg transition-all duration-200 hover:scale-105" title="上传附件">
                      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13" />
                      </svg>
                    </button>
                    <button className="p-2 text-gray-400 hover:text-green-500 hover:bg-green-50 rounded-lg transition-all duration-200 hover:scale-105" title="上传图片">
                      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                      </svg>
                    </button>
                    <button className="p-2 text-gray-400 hover:text-purple-500 hover:bg-purple-50 rounded-lg transition-all duration-200 hover:scale-105" title="语音输入">
                      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z" />
                      </svg>
                    </button>
                    
                    <div className="w-px h-4 bg-gray-300 mx-1"></div>
                    
                    {/* 状态信息 */}
                    <div className="flex items-center gap-2 text-xs text-gray-500">
                      <div className={`w-2 h-2 rounded-full ${
                        availableModels.find(m => m.id === currentModel)?.status === 'available' 
                          ? 'bg-green-400' 
                          : 'bg-yellow-400'
                      }`}></div>
                      {availableModels.find(m => m.id === currentModel)?.name || '模型'}
                    </div>
                  </div>
                  
                  <div className="flex items-center gap-3">
                    <button 
                      onClick={() => setInputValue('/help')}
                      className="text-xs text-gray-500 hover:text-blue-600 transition-colors px-2 py-1 rounded hover:bg-blue-50"
                    >
                      /help
                    </button>
                    <span className="text-xs text-gray-400">
                      {inputValue.length}/1000
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      {/* 右侧面板 - 智能摘要等 */}
      <div className="w-80 bg-white border-l border-gray-200 flex-shrink-0 p-4">
        {/* 智能摘要 - 基于设计方案 */}
        <div className="mb-6">
          <div className="flex items-center gap-2 mb-3">
            <span className="font-semibold text-gray-800">📝 智能摘要</span>
          </div>
          <div className="p-5 rounded-xl shadow-lg hover:shadow-xl transition-all bg-gradient-to-br from-orange-500 to-orange-600 text-white">
            <div className="font-semibold text-sm mb-2">对话要点</div>
            <div className="text-sm opacity-90">
              {messages.length <= 1 ? (
                '当前对话暂无内容，开始聊天后将自动生成智能摘要，帮助您快速回顾对话重点。'
              ) : (
                `已与${currentRole === 'emma' ? 'Emma心理咨询师' : currentRole === 'sophie' ? 'Sophie学术助手' : 'Mike面试教练'}进行了${Math.floor((messages.length - 1) / 2)}轮对话。主要讨论了${messages.filter(m => m.role === 'user').length > 0 ? '相关问题和解决方案' : '初步交流'}，对话氛围${currentRole === 'emma' ? '温暖支持' : currentRole === 'sophie' ? '学术严谨' : '专业高效'}。`
              )}
            </div>
          </div>
        </div>

        {/* 当前角色详细信息 */}
        <div className="mb-6">
          <div className="font-semibold text-gray-800 mb-3">👤 当前角色</div>
          {(() => {
            const currentRoleInfo = getCurrentRoleInfo();
            return (
              <div className="p-4 bg-gradient-to-r from-blue-50 to-purple-50 rounded-lg border border-blue-200">
                <div className="flex items-start gap-3 mb-3">
                  <span className="text-2xl">{currentRoleInfo.icon || '🎭'}</span>
                  <div className="flex-1">
                    <div className="font-medium text-blue-800">
                      {currentRoleInfo.name} - {currentRoleInfo.title || '智能助手'}
                    </div>
                    {currentRoleInfo.isCustom && (
                      <div className="inline-block px-2 py-1 bg-purple-100 text-purple-700 text-xs rounded-full mt-1">
                        自定义角色
                      </div>
                    )}
                  </div>
                </div>
                
                {/* 角色描述 */}
                <div className="text-sm text-gray-600 mb-3 leading-relaxed">
                  {currentRoleInfo.description || 
                   (currentRoleInfo.isCustom ? 
                     '这是您创建的自定义角色，将根据您设定的输入输出规范进行对话。' : 
                     '专业的AI助手，为您提供优质的对话体验。')}
                </div>
                
                {/* 自定义角色的输入输出规范 */}
                {currentRoleInfo.isCustom && (
                  <div className="space-y-2 pt-2 border-t border-blue-200">
                    <div className="text-xs text-gray-500">
                      <span className="font-medium text-gray-700">📥 输入规范：</span>
                      <div className="mt-1 text-gray-600 line-clamp-2 leading-relaxed">
                        {customRoles.find(r => r.id === currentRole)?.input_spec || '未设置'}
                      </div>
                    </div>
                    <div className="text-xs text-gray-500">
                      <span className="font-medium text-gray-700">📤 输出规范：</span>
                      <div className="mt-1 text-gray-600 line-clamp-2 leading-relaxed">
                        {customRoles.find(r => r.id === currentRole)?.output_spec || '未设置'}
                      </div>
                    </div>
                  </div>
                )}
                
                {/* 预设角色的特性标签 */}
                {!currentRoleInfo.isCustom && roleConfigs.find(r => r.id === currentRole)?.features && (
                  <div className="pt-2 border-t border-blue-200">
                    <div className="text-xs text-gray-500 mb-2">特性标签：</div>
                    <div className="flex flex-wrap gap-1">
                      {roleConfigs.find(r => r.id === currentRole)?.features?.slice(0, 4).map((feature: string) => (
                        <span key={feature} className="px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full">
                          {feature}
                        </span>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            );
          })()}
        </div>
        
        {/* 快捷操作 - 基于设计方案 */}
        <div>
          <div className="font-semibold text-gray-800 mb-3">⚡ 快捷操作</div>
          <div className="space-y-2">
            <button 
              onClick={handleExportChat}
              className="w-full flex items-center gap-3 p-3 rounded-lg hover:bg-gray-50 transition-all text-left border border-transparent hover:border-gray-200"
            >
              <span>💾</span>
              <span className="text-sm">导出对话</span>
            </button>
            
            <button 
              onClick={() => navigator.share ? navigator.share({title: 'MindMate对话', text: messages.slice(-1)[0]?.content || ''}) : alert('您的浏览器不支持分享功能')}
              className="w-full flex items-center gap-3 p-3 rounded-lg hover:bg-gray-50 transition-all text-left border border-transparent hover:border-gray-200"
            >
              <span>📤</span>
              <span className="text-sm">分享对话</span>
            </button>
            
            <button 
              onClick={handleClearChat}
              className="w-full flex items-center gap-3 p-3 rounded-lg hover:bg-gray-50 transition-all text-left border border-transparent hover:border-gray-200"
            >
              <span>🔄</span>
              <span className="text-sm">清空对话</span>
            </button>
            
            <button 
              onClick={() => {
                const lastMessage = messages.filter(m => m.role === 'assistant').slice(-1)[0];
                if (lastMessage) {
                  navigator.clipboard.writeText(lastMessage.content);
                  alert('AI回复已复制到剪贴板');
                } else {
                  alert('没有AI回复内容可复制');
                }
              }}
              className="w-full flex items-center gap-3 p-3 rounded-lg hover:bg-gray-50 transition-all text-left border border-transparent hover:border-gray-200"
            >
              <span>📋</span>
              <span className="text-sm">复制回复</span>
            </button>
            
            <button 
              onClick={() => alert('设置功能开发中...')}
              className="w-full flex items-center gap-3 p-3 rounded-lg hover:bg-gray-50 transition-all text-left border border-transparent hover:border-gray-200"
            >
              <span>⚙️</span>
              <span className="text-sm">设置</span>
            </button>
          </div>
        </div>
        
        {/* 系统状态 */}
        <div className="mt-6 pt-4 border-t">
          <div className="flex items-center gap-2 text-sm text-green-600">
            <div className="w-2 h-2 bg-green-500 rounded-full animate-pulse"></div>
            <span>系统运行正常</span>
          </div>
          <div className="text-xs text-gray-500 mt-1">
            基于《对话管理模块设计方案》
          </div>
        </div>
      </div>

      {/* 角色编辑器弹窗 */}
      <RoleEditor
        isOpen={isRoleEditorOpen}
        onClose={closeRoleEditor}
        onSave={handleSaveRole}
        editingRole={editingRole}
      />

      {/* 备忘录管理对话框 */}
      {isMemoDialogOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <div className="absolute inset-0 bg-black/50" onClick={() => setIsMemoDialogOpen(false)} />
          <div className="relative bg-white rounded-xl shadow-2xl w-full max-w-3xl max-h-[80vh] overflow-hidden">
            
            {/* 对话框头部 */}
            <div className="flex items-center justify-between p-6 border-b border-gray-200">
              <div>
                <h2 className="text-xl font-semibold text-gray-900">对话备忘录管理</h2>
                <p className="text-sm text-gray-600 mt-1">
                  当前对话：{conversationTurns} 轮 | {currentMemo ? `生成时间：${memoCreatedAt ? new Date(memoCreatedAt).toLocaleString() : ''}` : '尚未生成备忘录'}
                </p>
              </div>
              <button
                onClick={() => setIsMemoDialogOpen(false)}
                className="text-gray-400 hover:text-gray-600 transition-colors"
              >
                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>

            {/* 对话框内容 */}
            <div className="p-6 overflow-y-auto max-h-[60vh]">
              {currentMemo ? (
                <div>
                  {/* 备忘录内容 */}
                  <div className="mb-4">
                    <div className="flex items-center justify-between mb-3">
                      <h3 className="text-lg font-medium text-gray-900">备忘录内容</h3>
                      <div className="flex gap-2">
                        <button
                          onClick={() => {
                            setIsEditingMemo(!isEditingMemo);
                            if (!isEditingMemo) setTempMemo(currentMemo);
                          }}
                          className="px-3 py-1.5 text-sm bg-blue-100 text-blue-700 rounded-md hover:bg-blue-200 transition-colors"
                        >
                          {isEditingMemo ? '取消编辑' : '编辑备忘录'}
                        </button>
                        <button
                          onClick={async () => {
                            if (currentSessionId && await regenerateSessionMemo(currentSessionId)) {
                              alert('备忘录重新生成成功！');
                            } else {
                              alert('重新生成失败，请稍后重试');
                            }
                          }}
                          className="px-3 py-1.5 text-sm bg-green-100 text-green-700 rounded-md hover:bg-green-200 transition-colors"
                        >
                          重新生成
                        </button>
                      </div>
                    </div>
                    
                    {isEditingMemo ? (
                      <div>
                        <textarea
                          value={tempMemo}
                          onChange={(e) => setTempMemo(e.target.value)}
                          className="w-full h-40 p-3 border border-gray-300 rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-blue-500"
                          placeholder="编辑备忘录内容..."
                        />
                        <div className="flex justify-end gap-2 mt-3">
                          <button
                            onClick={() => {
                              setIsEditingMemo(false);
                              setTempMemo('');
                            }}
                            className="px-4 py-2 text-sm border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
                          >
                            取消
                          </button>
                          <button
                            onClick={async () => {
                              if (currentSessionId && await updateSessionMemo(currentSessionId, tempMemo)) {
                                setIsEditingMemo(false);
                                setTempMemo('');
                                alert('备忘录更新成功！');
                              } else {
                                alert('更新失败，请稍后重试');
                              }
                            }}
                            className="px-4 py-2 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                          >
                            保存修改
                          </button>
                        </div>
                      </div>
                    ) : (
                      <div className="bg-gray-50 border border-gray-200 rounded-lg p-4">
                        <div 
                          className="text-gray-800 leading-relaxed whitespace-pre-line"
                          dangerouslySetInnerHTML={{ __html: parseMarkdown(currentMemo) }}
                        />
                      </div>
                    )}
                  </div>
                </div>
              ) : (
                <div className="text-center py-8">
                  <div className="text-gray-400 text-6xl mb-4">📝</div>
                  <h3 className="text-lg font-medium text-gray-900 mb-2">尚未生成备忘录</h3>
                  <p className="text-gray-600 mb-4">
                    当对话轮次达到5轮时，系统会自动生成备忘录。当前对话：{conversationTurns} 轮
                  </p>
                  {conversationTurns >= 5 && (
                    <button
                      onClick={async () => {
                        if (currentSessionId && await regenerateSessionMemo(currentSessionId)) {
                          alert('备忘录生成成功！');
                        } else {
                          alert('生成失败，对话轮次可能不足或系统错误');
                        }
                      }}
                      className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                    >
                      手动生成备忘录
                    </button>
                  )}
                </div>
              )}
            </div>

            {/* 对话框底部 */}
            <div className="flex justify-end p-6 border-t border-gray-200 bg-gray-50">
              <button
                onClick={() => setIsMemoDialogOpen(false)}
                className="px-6 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-colors"
              >
                关闭
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 角色切换确认对话框 */}
      {isRoleSwitchModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          {/* 遮罩层 */}
          <div 
            className="absolute inset-0 bg-black bg-opacity-50 modal-overlay"
            onClick={cancelRoleSwitch}
          />
          
          {/* 对话框内容 */}
          <div className="relative bg-white rounded-xl shadow-xl w-full max-w-md modal-content">
            {/* 头部 */}
            <div className="flex items-center justify-between p-6 border-b border-gray-200">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-gradient-to-r from-orange-500 to-orange-600 rounded-lg flex items-center justify-center">
                  <span className="text-xl">⚠️</span>
                </div>
                <h2 className="text-xl font-bold text-gray-900">切换角色</h2>
              </div>
              <button
                onClick={cancelRoleSwitch}
                className="text-gray-400 hover:text-gray-600 transition-colors p-1"
              >
                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>

            {/* 内容 */}
            <div className="p-6">
              <div className="mb-4">
                <p className="text-gray-700 mb-3">
                  当前对话尚未结束，切换角色将：
                </p>
                <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4 mb-4">
                  <ul className="space-y-2 text-sm text-yellow-800">
                    <li className="flex items-start gap-2">
                      <span className="text-yellow-600">•</span>
                      <span>保存当前会话到历史记录</span>
                    </li>
                    <li className="flex items-start gap-2">
                      <span className="text-yellow-600">•</span>
                      <span>开始一个全新的对话会话</span>
                    </li>
                    <li className="flex items-start gap-2">
                      <span className="text-yellow-600">•</span>
                      <span>应用新角色的设定和提示词</span>
                    </li>
                  </ul>
                </div>
                <p className="text-gray-600 text-sm">
                  您可以随时从左侧会话列表中找回之前的对话。
                </p>
              </div>
            </div>

            {/* 底部操作按钮 */}
            <div className="flex items-center justify-end gap-3 p-6 border-t border-gray-200 bg-gray-50">
              <button
                onClick={cancelRoleSwitch}
                className="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
              >
                取消
              </button>
              <button
                onClick={confirmRoleSwitch}
                className="px-6 py-2 bg-gradient-to-r from-blue-500 to-blue-600 text-white rounded-lg hover:from-blue-600 hover:to-blue-700 transition-all flex items-center gap-2"
              >
                <span>🔄</span>
                切换角色
              </button>
            </div>
          </div>
        </div>
      )}
      
      {/* 登录弹窗 */}
      {showLoginDialog && (
        <Login
          onLoginSuccess={handleLoginSuccess}
          onClose={() => setShowLoginDialog(false)}
        />
      )}
      
      {/* 确认删除弹窗 */}
      <ConfirmModal
        isOpen={confirmModal.isOpen}
        title={confirmModal.title}
        message={confirmModal.message}
        confirmText="删除"
        cancelText="取消"
        type="danger"
        onConfirm={confirmModal.onConfirm}
        onCancel={() => setConfirmModal(prev => ({ ...prev, isOpen: false }))}
      />
      
      {/* 备忘录弹窗 */}
      <MemoModal
        isOpen={memoModal.isOpen}
        sessionId={memoModal.sessionId}
        sessionTitle={memoModal.sessionTitle}
        onClose={() => setMemoModal(prev => ({ ...prev, isOpen: false }))}
      />
      
      {/* 编辑确认弹窗 */}
      <EditConfirmModal
        isOpen={showEditConfirm}
        onConfirm={submitEdit}
        onCancel={() => {
          setShowEditConfirm(false);
          setEditPreview(null);
        }}
        deleteCount={editPreview?.deleteCount || 0}
        previewMessages={editPreview?.previewMessages}
        hasMore={editPreview?.hasMore}
        memoImpact={editPreview?.memoImpact}
        currentMemoExists={editPreview?.currentMemoExists}
      />
      
      {/* 备忘录过时提示横幅 */}
      <MemoOutdatedBanner />
    </div>
  );
}

export default App;